package cc.fs.zhihuapp.ui.fragment;

import android.app.Fragment;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.convenientbanner.CBPageAdapter;
import com.bigkoo.convenientbanner.CBViewHolderCreator;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.facebook.drawee.view.SimpleDraweeView;

import java.util.ArrayList;

import cc.fs.zhihuapp.R;
import cc.fs.zhihuapp.model.Category;
import cc.fs.zhihuapp.model.DayNews;
import cc.fs.zhihuapp.model.News;
import cc.fs.zhihuapp.model.Theme;
import cc.fs.zhihuapp.rest.asynchttp.Api;
import cc.fs.zhihuapp.ui.activity.MainActivity;
import cc.fs.zhihuapp.ui.activity.NewsActivity;
import cc.fs.zhihuapp.ui.adapter.DetailAdapter;
import cc.fs.zhihuapp.ui.adapter.ThemeAdapter;
import cc.fs.zhihuapp.ui.base.BaseFragment;
import cc.fs.zhihuapp.ui.view.EmptyView;
import cc.fs.zhihuapp.utils.MyCallback;
import cc.fs.zhihuapp.utils.QuickReturnUtils;
import cc.fs.zhihuapp.utils.RecyclerViewFooter;

/**
 * Created by fostion on 2015/9/7.
 */
public class DataFragment extends BaseFragment {
    ActionBarDrawerToggle toogle;
    DrawerLayout mDrawerLayout;
    EmptyView emptyView;
    SimpleDraweeView image;
    ArrayList<News> list;
    ArrayList<Theme> themes;
    RecyclerView recyclerView;
    RecyclerView menuView;
    RelativeLayout headContain;
    ConvenientBanner<News> convenientBanner;
    LinearLayoutManager dataManager;
    LinearLayoutManager themeManager;
    DetailAdapter detailAdapter;
    ThemeAdapter themeAdapter;
    String updateTime = "20150820";
    RecyclerViewFooter footer = null;
    MainActivity parent;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_data, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mDrawerLayout = (DrawerLayout) view.findViewById(R.id.drawerLayout);
        emptyView = (EmptyView) view.findViewById(R.id.emptyView);
        image = (SimpleDraweeView) view.findViewById(R.id.image);
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        menuView = (RecyclerView) view.findViewById(R.id.menuLayout);
        headContain = (RelativeLayout) view.findViewById(R.id.containLayout);
        parent = (MainActivity)getActivity();

        dataManager = new LinearLayoutManager(parent);
        list = new ArrayList<>();
        detailAdapter = new DetailAdapter(getActivity(),list);
        recyclerView.setLayoutManager(dataManager);
        recyclerView.setAdapter(detailAdapter);

        themeManager = new LinearLayoutManager(parent);
        themes = new ArrayList<>();
        themeAdapter = new ThemeAdapter(getActivity(),themes);
        menuView.setLayoutManager(themeManager);
        menuView.setAdapter(themeAdapter);

        detailAdapter.setOnItemClick(new DetailAdapter.OnItemClick() {
            @Override
            public void onItemClick(News news) {
                NewsActivity.start(parent, news.getId());
            }
        });

        themeAdapter.setOnItemClick(new ThemeAdapter.OnItemClick() {
            @Override
            public void click(Theme theme) {
                mDrawerLayout.closeDrawers();
            }
        });
        emptyView.setOnRetryClick(new EmptyView.OnRetryClick() {
            @Override
            public void retryClick() {
                setUpApi();
            }
        });
        setUpToogle();
        setUpApi();
    }

    void setUpToogle(){
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);
        //drawerArrow
        toogle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout,((MainActivity)getActivity()).getToolbar() , R.string.opean, R.string.close) {
            @Override
            public void onDrawerOpened(View drawerView) {
                getActivity().invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                getActivity().invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };
        mDrawerLayout.setDrawerListener(toogle);
        toogle.syncState();
    }


    void setUpBanner(ArrayList<News> topNews) {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT, android.view.ViewGroup.LayoutParams.MATCH_PARENT);
        convenientBanner = new ConvenientBanner(getActivity());
        convenientBanner.setLayoutParams(params);
        convenientBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        }, topNews)
                .setPageIndicator(new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused})
                        //设置翻页的效果，不需要翻页效果可用不设
                .setPageTransformer(ConvenientBanner.Transformer.DefaultTransformer);
        headContain.addView(convenientBanner);
        headContain.invalidate();
        convenientBanner.startTurning(3000);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        toogle.onConfigurationChanged(newConfig);
    }

    public void syncState() {
        toogle.syncState();
    }

    public boolean optionsItemSelected(MenuItem item) {
        if (toogle.onOptionsItemSelected(item)) {
            return true;
        }
        return false;
    }

    private ActionBar getActionBar() {
        return ((AppCompatActivity) getActivity()).getSupportActionBar();
    }

    String parseDate(String date) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(date.subSequence(0, 4)).append("年");
        stringBuilder.append(date.subSequence(4, 6)).append("月");
        stringBuilder.append(date.subSequence(6, 8)).append("日");
        return stringBuilder.toString();
    }

    @Override
    public void onResume() {
        if (convenientBanner != null) {
            convenientBanner.startTurning(3000);
        }
        super.onResume();
    }

    @Override
    public void onPause() {
        if (convenientBanner != null) {
            convenientBanner.stopTurning();
        }
        super.onPause();
    }

    @Override
    public void onDestroy() {
        if(convenientBanner != null){
            convenientBanner.stopTurning();
        }
        super.onDestroy();
    }

    void setUpApi() {
        Api.getLastNews(new MyCallback.NetworkCallback0<DayNews>() {
            @Override
            public void success(DayNews dayNews) {
                try {
                    if (dayNews != null) {
                        list.clear();
                        updateTime = dayNews.getDate();
                        News tagNews = new News(true, "今天");
                        list.add(tagNews);
                        list.addAll(dayNews.getStories());
                        setUpBanner(dayNews.getTop_stories());
                        emptyView.setErrorState(EmptyView.HIDEN_LAYOUT);

                        footer = RecyclerViewFooter.create(recyclerView, new Runnable() {
                            @Override
                            public void run() {
                                Api.getOldNews(updateTime, new MyCallback.NetworkCallback0<DayNews>() {
                                    @Override
                                    public void success(DayNews oldDateNews) {
                                        updateTime = oldDateNews.getDate();
                                        News tagNews = new News(true, parseDate(updateTime));
                                        list.add(tagNews);
                                        list.addAll(oldDateNews.getStories());
                                        detailAdapter.notifyDataSetChanged();
                                        footer.loadFinish();
                                    }

                                    @Override
                                    public void failure(String errror) {

                                    }
                                });
                            }
                        });
                        recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {

                            @Override
                            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                                super.onScrollStateChanged(recyclerView, newState);
                            }

                            @Override
                            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                                float scrollY = -QuickReturnUtils.getScrollY(recyclerView, 1) * 0.7f;
                                headContain.setTranslationY(scrollY);
                            }
                        });
                    }
                } finally {
                    detailAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void failure(String errror) {
                detailAdapter.setIsLoadMore(false);
                emptyView.setErrorState(EmptyView.ERROR_NETWORK);
            }
        });

        Api.getCategory(new MyCallback.NetworkCallback0<Category>() {
            @Override
            public void success(Category category) {
                themes.clear();
                themes.addAll(category.getOthers());
                themeAdapter.notifyDataSetChanged();
            }

            @Override
            public void failure(String errror) {

            }
        });
    }

    static class NetworkImageHolderView implements CBPageAdapter.Holder<News> {

        View view;
        SimpleDraweeView image;
        TextView title;
        RelativeLayout bottomLayout;

        @Override
        public View createView(Context context) {
            view = LayoutInflater.from(context).inflate(R.layout.item_head_contain, null);
            image = (SimpleDraweeView) view.findViewById(R.id.image);
            title = (TextView) view.findViewById(R.id.title);
            bottomLayout = (RelativeLayout) view.findViewById(R.id.bottomLayout);
            return view;
        }

        @Override
        public void UpdateUI(final Context context, int i, final News news) {
            image.setImageURI(Uri.parse(news.getImage()));
            title.setText(news.getTitle());
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    NewsActivity.start(context, news.getId());
                }
            });
        }

    }
}
